<template>
	<div>
		<!-- 面包屑导航区 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>系统管理</el-breadcrumb-item>
			<el-breadcrumb-item>员工管理</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 卡片视图区域 -->
		<el-card>
			<!-- 搜索添加区 -->
			<el-row :gutter="20">
				<el-form :inline="true" :model="queryInfo" class="demo-form-inline">
					<el-form-item label="姓名">
						<el-input v-model="queryInfo.LoginName" placeholder=""></el-input>
					</el-form-item>
					<el-form-item label="状态">
						<el-select v-model="queryInfo.IsLockout" placeholder="">
							<el-option label="请选择" value=""></el-option>
							<el-option label="被锁定" value="1"></el-option>
							<el-option label="未被锁定" value="0"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="onSubmit">查询</el-button>
					</el-form-item>
					<el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
				</el-form>
			</el-row>
			<!--用户列表区  -->
			<el-table :data="userlist" border stripe>
				<el-table-column label="#" prop="Id"></el-table-column>
				<el-table-column label="姓名" prop="LoginName"></el-table-column>
				<el-table-column label="邮箱" prop="ProtectEmail"></el-table-column>
				<el-table-column label="电话" prop="ProtectTel"></el-table-column>
				<!-- <el-table-column label="角色" prop="Name"></el-table-column> -->
				<el-table-column label="创建时间" prop="CreateTime"></el-table-column>
				<el-table-column label="状态" >
					<!-- <template slot-scope="scope">
						
						<el-switch v-model="scope.row.IsLockout" 
						 active-value=0
						 inactive-value=1
						 active-text="已被锁定" 
						 inactive-text="违背锁定" 
						 active-color="#13ce66"
                         inactive-color="#ff4949" 
	                    @change="userStateChanged(scope.row)">
						</el-switch>
					</template> -->
					<template v-slot="scope">
						<el-tooltip content="绿:锁定 红:未锁定" placement="top">
						<el-switch
							v-model="scope.row.IsLockout"
							active-color="#13ce66"
							inactive-color="#ff4949"
							@change="changeStatus(scope.row)"
							:active-value="1"
							:inactive-value="0"
						></el-switch>
						</el-tooltip>
					</template>
				</el-table-column>
				<el-table-column label="锁定时间" prop="LockTime"></el-table-column>
				<el-table-column label="操作" width="240px">
					<template v-slot="scope">
						<!-- 分配角色按钮 -->
						<el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
							<el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row.Id)"></el-button>
						</el-tooltip>
						<!-- 修改按钮 -->
						<el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.Id)"></el-button>
						<!-- 删除按钮 -->
						<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.Id)"></el-button>
						<el-tooltip effect="dark" content="重置密码" placement="top" :enterable="false">
								<el-button type="info" icon="el-icon-refresh" size="mini" @click="refreshById(scope.row.Id)"></el-button>
						</el-tooltip>
					
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
			 :page-sizes="[5, 10, 20, 50]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="count">
			</el-pagination>
		</el-card>


		<!-- 添加用户的对话框 -->
		<el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
			<!-- 内容主题区域 -->
			<el-form :model="addForm" :rules="addFromRules" ref="addFormRef" label-width="70px">
				<el-form-item label="用户名 " prop="LoginName">
					<el-input v-model="addForm.LoginName"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="Password">
					<el-input v-model="addForm.Password" type="password"></el-input>
				</el-form-item>
				<el-form-item label="邮箱 " prop="ProtectEmail">
					<el-input v-model="addForm.ProtectEmail"></el-input>
				</el-form-item>
				<el-form-item label="手机 " prop="ProtectTel">
					<el-input v-model="addForm.ProtectTel"></el-input>
				</el-form-item>
			</el-form>
			<!-- 底部区域 -->
			<span slot="footer" class="dialog-footer">
				<el-button @click="addDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="addUser">确定</el-button>
			</span>
		</el-dialog>
		<!-- 修改用户的对话框 -->
		<el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
			<el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
				<el-form-item label="用户名">
					<el-input v-model="editForm.LoginName" disabled></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="editForm.ProtectEmail"></el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="mobile">
					<el-input v-model="editForm.ProtectTel"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="editUserInfo">确定</el-button>
			</span>
		</el-dialog>


		<el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
			<div>
				 <el-transfer v-model="value" :data="datas"  :titles="['系统所有角色', '当前所有角色']"  @change="handleChange"></el-transfer>
			</div>
			<!-- <div slot="footer" class="dialog-footer">
      			<el-button @click="upPage" size="small">上一步</el-button>
      			<el-button type="primary" @click="addDatasource" size="small">保存</el-button>
    		</div> -->

		</el-dialog>

	</div>
</template>

<script>
	export default {
		data() {
// const generateData = _ => {
//         const datas = [];
//         for (let i = 1; i <= 15; i++) {
//           datas.push({
//             key: i,
//             label: `备选项 ${ i }`,
//           });
//         }
//         return datas;
//       }
			//验证邮箱的规则
			var checkEmail = (rule, value, cb) => {
				//验证邮箱的正则表达式
				const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
				if (regEmail.test(value)) {
					//合法的邮箱
					return cb()
				}
				cb(new Error('请输入合法的邮箱'))
			}
			//验证手机号规则
			var checkMobile = (rule, value, cb) => {
				const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

				if (regMobile.test(value)) {
					//合法的手机号
					return cb()
				}
				cb(new Error('请输入合法的手机号'))
			}

			return {
				datas:{},
        		value: [],
				userId:'',
				//  relateTableStr: '',
     			//  obj: {},
				 // movedKey = [],
				//获取用户列表的参数对象
				queryInfo: {
					LoginName:"",
					IsLockout: ""
					//当前的页数
				},
				userlist: [], //table数据

				page: 1,
				//当前每页显示多少条数据
				limit: 10,
				count: 0,
				//控制添加用户对话框的显示与隐藏
				addDialogVisible: false,
				//添加用户的表单数据
				addForm: {
					LoginName: '',
					Password: '',
					ProtectEmail: '',
					ProtectTel: '',
					//CreateTime:""

				},
				//添加表单的验证规则对象
				addFromRules: {
					LoginName: [{
							required: true,
							message: '请输入用户名',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 10,
							message: '用户名的长度在3~10个字符之间',
							trigger: 'blur'
						}
					],
					Password: [{
							required: true,
							message: '请输入密码',
							trigger: 'blur'
						},
						{
							min: 4,
							max: 15,
							message: '密码的长度在4~15个字符之间',
							trigger: 'blur'
						}
					],
					ProtectEmail: [{
							required: true,
							message: '请输入邮箱',
							tigger: 'blur'
						},
						{
							validator: checkEmail,
							tigger: 'blur'
						}
					],
					ProtectTel: [{
							required: true,
							message: '请输入手机号',
							tigger: 'blur'
						},
						{
							validator: checkMobile,
							tigger: 'blur'
						}
					]
				},
				//控制修改用户对话框的显示与隐藏
				editDialogVisible: false,
				//查询到的用户信息对象
				editForm: {},
				// 修改表单的验证规则对象
				editFormRules: {
					email: [{
							required: true,
							message: '请输入用户邮箱',
							trigger: 'blur'
						},
						{
							validator: checkEmail,
							trigger: 'blur'
						},
					],
					mobile: [{
							required: true,
							message: '请输入用户手机',
							trigger: 'blur'
						},
						{
							validator: checkMobile,
							trigger: 'blur'
						}
					]
				},
				//控制分配角色对话框的显示与隐藏
				setRoleDialogVisible: false,
				// 需要被分配角色的用户信息
				userInfo: {},
				//所有角色的数据列表
				roleslist: {},
				//已选中的角色Id值
				selectedRoleId: ''
			}
		},
		created() {
			this.getUserList()
		},
		methods: {
			async getUserList() {
				const {
					data: res
				} = await this.$http.get('api/Users/GetUsersList?page=' + this.page +
					"&limit=" + this.limit +
					"&LoginName=" + this.queryInfo.LoginName +
					"&IsLockout=" + this.queryInfo.IsLockout)
				console.log(res)
				if (res.code !== 0) {
					return this.$message.error('获取用户列表失败')
				}
				this.userlist = res.data
				this.count = res.count

			},
			onSubmit(){
				this.getUserList();
			},
			
			// 监听pagesize改变的事件
			handleSizeChange(newSize) {
				//console.log(newSize)
				this.limit = newSize
				this.getUserList()
			},
			// 监听页码值改变的事件
			handleCurrentChange(newPage) {
				//console.log(newPage)
				this.page = newPage
				this.getUserList()
			},
			
			async changeStatus(row) {
				this.switchrow = row;
				const { data: res } = await this.$http.post('api/Users/Updatestatus', this.switchrow);
				console.log(res)
				if (res.code !== 0) {
					this.$message.error(res.msg);
				}
				this.$message.success(res.msg);
				this.getUserList()
				},
			//监听添加用户对话框关闭事件
			addDialogClosed() {
				this.$refs.addFormRef.resetFields()
			},
			//点击按钮，添加新用户
			addUser() {
				this.$refs.addFormRef.validate(async valid => {
					if (!valid) return
					//可以发起添加用户的网络请求
					const {
						data: res
					} = await this.$http.post('api/Users/AddUserDel', this.addForm)
					console.log(res);
					if (res.code !== 0) {
						this.$message.error('添加用户失败!')
					}
					this.$message.success('添加用户成功!')
					//隐藏添加用户的对话框
					this.addDialogVisible = false
					this.getUserList()
				})
			},
			
			//展示编辑用户的对话框
			async showEditDialog(Id) {
				console.log(Id)
				const {
					data: res
				} = await this.$http.get('api/Users/GetUserById?Id=' + Id)
				console.log(res)
				if (res.code !== 0) {
					return this.$message.error('查询用户信息失败!')
				}
				this.editForm = res.data
				this.editDialogVisible = true
			 },
			//监听修改用户对话框的关闭事件
			editDialogClosed() {
				this.$refs.editFormRef.resetFields()
			},
			//修改用户信息并提交
			editUserInfo() {
				this.$refs.editFormRef.validate(async valid => {
					if (!valid) return
					//发起修改用户信息的数据请求
					const {
						data: res
					} = await this.$http.post('api/Users/GetUserEdit',this.editForm)
					console.log(res)
					
					if (res.code !== 0) {
						return this.$message.error('更新用户信息失败!')
					}
					//关闭对话框
					this.editDialogVisible = false
					//刷新数据列表
					this.getUserList()
					//提示修改成功
					this.$message.success('更新用户信息成功!')
				})
			},
			//根据Id删除对应的用户信息
			async removeUserById(Id) {
				//弹框询问用户是否删除数据
				const confirmResult = await this.$confirm(
					'此操作将永久删除该用户, 是否继续?',
					'提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}
				).catch(err => err)
				//如果用户确认删除，则返回值为字符串 comfirm
				//如果用户取消删除 则返回值为字符串 cancel
				if (confirmResult !== 'confirm') {
					return this.$message.info('已取消删除')
				}
				const {
					data: res
				} = await this.$http.get('api/Users/GetUserDelById?Id=' + Id)
				console.log(res)
				if (res.code !== 0) {
					return this.$message.error(res.msg)
				}
				this.$message.success('删除用户成功!')
				this.getUserList()
			},
			//根据Id重置对应的用户信息
			async refreshById(Id) {
				//弹框询问用户是重置
				const confirmResult = await this.$confirm(
					'此操作将重置该用户密码, 默认为123456是否继续?',
					'提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}
				).catch(err => err)
				//如果用户确认删除，则返回值为字符串 comfirm
				//如果用户取消删除 则返回值为字符串 cancel
				if (confirmResult !== 'confirm') {
					return this.$message.info('已取消重置')
				}
				const {
					data: res
				} = await this.$http.get('api/Users/GetUserRefreshById?Id=' + Id)
				console.log(res)
				if (res.code !== 0) {
					return this.$message.error(res.msg)
				}
				this.$message.success('重置用户成功!')
				this.getUserList()
			},
			//展示分配角色的对话框
			async setRole(Id) {
				console.log(Id)
				//this.setRoleDialogVisible = true
				//在展示对话框之前，获取所有角色的列表
				const {
					data: res
				} = await this.$http.get('api/Users/GetRoles?Id='+Id)
				console.log(res)
				if (res.code !== 0) {
					this.datas = res.data
					this.value =  res.valus
					this.userId = res.userId
					this.setRoleDialogVisible = true
					return this.$message.success('该用户没有角色 请添加!')
					
				}
				this.datas = res.data
				this.value = res.valus
				this.userId = res.userId
				this.setRoleDialogVisible = true
			},
			handleChange(value, direction, movedKeys) {
       				//console.log(value, direction, movedKeys);
					console.log(value);
					console.log(direction);
					console.log(movedKeys);
					//const roleId=value[0];
					var movedKey = "";
					for (let i = 0; i < movedKeys.length; i++) {
						movedKey=movedKey+movedKeys[i]+","
					}
					movedKey = movedKey.substring(0, movedKey.length-1)
					console.log(movedKey);
					console.log(movedKeys.length);
					this.$message=this.$message;
					if(direction=="right"){
						this.$http.get('api/Users/GetUsersRolesAdd?userId='+this.userId+"&movedKey="+movedKey)
						.then(res=>{
							console.log(res)
							if(res.data.code==0){
								//alert(res.data.msg)
								this.$message.success(res.data.msg)
							}else{
								return this.$message.success(res.data.msg)
							}
						})
					}
					if(direction=="left"){
						this.$http.get('api/Users/GetUsersRolesDel?userId='+this.userId+"&movedKey="+movedKey)
						.then(res=>{
							console.log(res)
							if(res.data.code==0){
								//alert(res.data.msg)
								  this.$message.success(res.data.msg)
							}else{
								return this.$message.success(res.data.msg)
							}
						})

					}

					
					
      		}


		},
		mounted: function() {
			this.getUserList()
		}
	}
</script>

<style Lang="less" scoped>

</style>
